from flask import Blueprint, render_template, request, jsonify, flash, redirect, url_for
from app.models.companys import Companys
from app.forms.common import AjaxDeleteForm
from app.forms.companys import CompanysForm
from flask_login import login_required
from app.decorators import permission_required
import json

bp = Blueprint('companys', __name__)


@bp.before_request
@login_required
def before_request():
    pass


@bp.context_processor
def make_template_context():
    return dict(county=Companys.query.filter(Companys.pid==None).all())


@bp.route('/')
@permission_required('SUB_INDEX')
def index():
    county = request.args.get('county', None, type=int)
    query = Companys.query.filter(Companys.pid!=None)
    if county:
        query = query.filter(Companys.pid == county)
    model = query.all()

    return render_template('admin/companys/index.html', model=model)


@bp.route('/delete/<int:id>')
@permission_required('SUB_DELETE')
def delete(id):
    model = Companys.query.get_or_404(id)
    if model.users:
        flash('请先删除单位下面的用户!', 'danger')
        return redirect(url_for('companys.index'))
    model.delete(True)
    flash('删除成功!', 'success')
    return redirect(url_for('companys.index'))


@bp.route('/create', methods=['GET', 'POST'])
@permission_required('SUB_CREATE')
def create():
    form = CompanysForm()
    model = Companys()
    if model.save(form):
        flash('成功创建单位{}'.format(model.name), 'success')
        return redirect(url_for('companys.index'))
    return render_template('admin/companys/create.html', form=form)


@bp.route('/update/<int:id>', methods=['GET', 'POST'])
@permission_required('SUB_UPDATE')
def update(id):
    form = CompanysForm()
    model = Companys.query.get_or_404(id)
    if model.save(form):
        flash('修改成功', 'success')
        return redirect(url_for('companys.index'))

    form.load(model)
    return render_template('admin/companys/update.html', form=form)


@bp.route('/ajax_delete', methods=['POST'])
@permission_required('SUB_AJAX_UPDATE')
def ajax_delete():
    form = AjaxDeleteForm()
    if form.validate_on_submit():
        for i in json.loads(form.ids.data):
            model = Companys.query.get_or_404(i)
            if model.users:
                return jsonify({'success': False, 'message': '{}未删除,请先删除单位下面的用户!'.format(model.name)})
            model.delete(True)

    if form.errors:
        flash(form.errors, 'danger')

    return jsonify({'success': True, 'message': '删除成功'})
